﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Willow.IRepository;
using Willow.IService;
using Willow.Model;
using Willow.Extensions;
using Willow.IService.Auth;
namespace Willow.Service.Auth
{
    public class ModuleService : BaseService<Auth_Module>, IModuleService
    {

        IRepository<Auth_RoleModule> RoleModuleRepository;
        IRepository<Auth_RoleAction> RoleActionRepository;

        public ModuleService(IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {
            RoleModuleRepository = unitOfWork.GetStandardRepository<Auth_RoleModule>();
            RoleActionRepository = unitOfWork.GetStandardRepository<Auth_RoleAction>();
        }

        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="id">The identifier.</param>
        public void LogicalDelete(Guid id)
        {
            string filterId = id.ToString();
            var lstOrg = base.Filter(p => p.FullParentId.Contains(filterId)).ToList();
            foreach (var org in lstOrg)
            {
                org.IsDelete = true;
            }
            UnitOfWork.SaveChanges();
        }
        /// <summary>
        /// 分配模块和功能
        /// </summary>
        /// <param name="roleId">The role identifier.</param>
        /// <param name="moduleIds">The module ids.</param>
        /// <param name="actionIds">The action ids.</param>
        public void DistributeModuleAndAction(Guid roleId, Guid[] moduleIds, Guid[] actionIds)
        {
            //删除旧角色菜单信息
            var lstRoleModule = RoleModuleRepository.Filter(p => p.RoleId == roleId).ToList();
            foreach (var item in lstRoleModule)
            {
                RoleModuleRepository.Delete(item);
            }

            //添加新角色菜单信息
            foreach (var moduleId in moduleIds.OrEmptyIfNull())
            {
                var roleModule = new Auth_RoleModule
                {
                    Id = Guid.NewGuid(),
                    RoleId = roleId,
                    ModuleId = moduleId
                };
                RoleModuleRepository.Create(roleModule);
            }

            //删除旧角色功能信息
            var lstRoleAction = RoleActionRepository.Filter(p => p.RoleId == roleId).ToList();
            foreach (var item in lstRoleAction)
            {
                RoleActionRepository.Delete(item);
            }

            //添加新角色功能信息
            foreach (var actionId in actionIds.OrEmptyIfNull())
            {
                var roleModule = new Auth_RoleAction
                {
                    Id = Guid.NewGuid(),
                    RoleId = roleId,
                    ActionId = actionId
                };
                RoleActionRepository.Create(roleModule);
            }

            UnitOfWork.SaveChanges();
        }
    }
}
